package shop.controller.front.organize;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import shop.core.FrontBaseController;
import shop.core.Services;
import shop.core.common.bean.JSONResult;
import shop.core.plugins.sms.SMS;
import shop.core.plugins.sms.SMSVerifyCodeResult;
import shop.core.util.MD5;
import shop.services.front.account.AccountService;
import shop.services.front.account.bean.Account;
import shop.services.front.area.AreaService;
import shop.services.front.area.bean.Area;
import shop.services.front.organize.OrganizeService;
import shop.services.front.organize.bean.Organize;
import shop.services.manage.system.bean.Menu;
import shop.services.manage.system.bean.MenuItem;
import shop.services.manage.system.bean.Role;
import shop.services.manage.system.bean.User;
import shop.services.manage.system.impl.MenuService;
import shop.services.manage.system.impl.RoleService;
import shop.services.manage.system.impl.UserService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * Created by Administrator on 2017/4/17.
 */
@Controller
@RequestMapping("/front/organize")
public class OrganizeController extends FrontBaseController<Organize> {
    @Resource
    private AreaService areaService;
    @Resource
    private AccountService accountService;
    @Autowired
    private RoleService roleService;
    @Resource
    private OrganizeService organizeService;
    @Resource
    private UserService userService;
    @Resource
    private MenuService menuService;
    @Override
    public Services<Organize> getService() {
        return organizeService;
    }


    /**
     * 页面跳转方法
     *
     * @return
     */
    @RequestMapping("/toOrganizeList")
    public String toOrganizeList() {
        return "/front/organize/organizeList";
    }

    @RequestMapping("/toOrganizeDetail")
    public String toOrganizeDetail() {
        return "/front/organize/organizedetail";
    }

    @RequestMapping("/toOrganizeJoin")
    public String toOrganizeJoin() {
        return "/front/organize/organizeJoin";
    }

    @RequestMapping("/toOfflineDetail")
    public String toOfflineDetail() {
        return "/front/organize/offlineDetail";
    }

    @RequestMapping("/toOfflineJoin")
    public String toOfflineJoin() {
        return "/front/organize/offlineJoin";
    }

    /**
     * 查询地级市
     *
     * @param area
     * @return
     */
    @RequestMapping(value = "/selectArea",  method = RequestMethod.GET)
    @ResponseBody
    public JSONResult selectArea(Area area) {
        JSONResult jsonResult = new  JSONResult();
        List<Area> list = areaService.selectList(area);
        jsonResult.setData(list);
        jsonResult.setSuccess(true);
        return jsonResult;
    }

    /**
     * 移动端机构登录
     * @param user 登录用户
     * @return 成功时返回用户信息 失败时返回失败信息
     */
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    @ResponseBody
    public JSONResult login(User user,HttpSession session){
        JSONResult rs=new JSONResult();
        if (StringUtils.isBlank(user.getUsername()) || StringUtils.isBlank(user.getPassword())){
            rs.setMessage("账户和密码不能为空!");
            rs.setSuccess(false);
            return rs;
        }
        logger.info("用户登录:{}", user.getUsername());
        user.setPassword(MD5.md5(user.getPassword()));
        User u = userService.login(user);
        if (u == null) {
            rs.setMessage("登陆失败，账户或密码错误！");
            rs.setSuccess(false);
            logger.error("登陆失败，账户或密码错误,{}", user.getUsername());
            return rs;
        }else if(!u.getStatus().equals(User.user_status_y)){
            rs.setMessage("帐号已被禁用，请联系管理员!");
            rs.setSuccess(false);
            logger.error("帐号已被禁用，请联系管理员,{}", u.getUsername());
            return rs;
        }
        u.setUsername(user.getUsername());
        session.setAttribute("userInfo", u);
        //解析用户的数据库权限，以后可以进行DB权限限制
        if(StringUtils.isNotBlank(u.getRole_dbPrivilege())){
            String[] dbPriArr = u.getRole_dbPrivilege().split(",");
            if(u.getDbPrivilegeMap()==null){
                u.setDbPrivilegeMap(new HashMap<String, String>());
            }else{
                u.getDbPrivilegeMap().clear();
            }
            if(dbPriArr.length!=0){
                for(int i=0;i<dbPriArr.length;i++){
                    u.getDbPrivilegeMap().put(dbPriArr[i], dbPriArr[i]);
                }
            }
        }
        //用户可访问的菜单写入session
        Collection<MenuItem> userMenus = loadMenus(u);
        session.setAttribute("userMenus", userMenus);
        if (session.getAttribute("userOpenId")!=null){
            if(!StringUtils.isBlank(u.getOpenID())&&!u.getOpenID().equals(session.getAttribute("userOpenId").toString())){
                rs.setMessage("该微信号已与其他账号绑定，登录失败");
                rs.setSuccess(false);
                return rs;
            }
            u.setOpenID(session.getAttribute("userOpenId").toString());
            userService.update(u);
        }
//        else {
//            rs.setMessage("请使用微信登录");
//            rs.setSuccess(false);
//            return rs;
//        }
        Organize organize=new Organize();
        organize.setPrincipalPhone(u.getUsername());
        organize=organizeService.selectByPrincipalPhone(organize);
        session.setAttribute("organizeInfo",organize);
        rs.setData(organize);
        rs.setMessage("登录成功");
        rs.setSuccess(true);
        return rs;
    }

    /**
     * 机构注册方法
     *
     * @param request
     * @param organize 信息
     * @return
     * @throws Exception
     */
    @Override
    @RequestMapping(value = "/insertJson", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult insertJson(HttpServletRequest request, @ModelAttribute("organize") Organize organize) throws Exception {
        jsonResult = new JSONResult();
        HttpSession session=request.getSession();
        // SmsId 短信唯一码   SmsContent 短信内容
        String smsId = request.getParameter("SmsId").toString();
        String smsContent = request.getParameter("SmsContent").toString();

        SMS sms = new SMS();
        SMSVerifyCodeResult rs = sms.verifyCode(smsId, smsContent);
        if (!rs.getSuccess()) {
            jsonResult.setSuccess(false);
            jsonResult.setMessage("短信验证码错误！");
            return jsonResult;
        }
        List<Account> accountList = accountService.selectList(new Account());
        List<User> userList = userService.selectList(new User());
        for (User anUserList : userList) {
            if (anUserList.getUsername().equals(organize.getPrincipalPhone())) {
                jsonResult.setSuccess(false);
                jsonResult.setMessage("该手机已注册过机构，不可重复注册");
                return jsonResult;
            }
        }
        for (Account anAccountList : accountList) {
            if (anAccountList.getPhone().equals(organize.getPrincipalPhone())) {
                jsonResult.setSuccess(false);
                jsonResult.setMessage("该手机已注册为志愿者，不可注册为机构");
                return jsonResult;
            }
        }
        organizeService.insert(organize);
//      插入用户表做登录验证
        User user = new User();
        user.setUsername(organize.getPrincipalPhone());
        user.setPassword(MD5.md5(request.getParameter("password")));
        //      绑定微信
        if (session.getAttribute("userOpenId")!=null){
            user.setOpenID(session.getAttribute("userOpenId").toString());
        }
//        获取角色信息
        Role role = roleService.selectByRoleName("机构账号");
        user.setRid(role.getId());
        user.setNickname(organize.getPrincipalPhone());
        user.setStatus("y");
        userService.insert(user);
        return jsonResult;
    }

    /**
     * 加载用户菜单
     * @param u
     * @return
     */
    private Collection<MenuItem> loadMenus(User u) {
		/*
		 * 首先，加载顶级目录或页面菜单
		 */
        Map<String, String> param = new HashMap<String, String>();
        if (u != null && u.getRid() != null) {
            param.put("rid", u.getRid());//角色ID
        }
        List<Menu> menus = menuService.selectList(param);
        //创建菜单集合
        LinkedHashMap<String, MenuItem> root = new LinkedHashMap<String, MenuItem>();
        //循环添加菜单到菜单集合
        for (Menu menu : menus) {
            MenuItem item = new MenuItem(menu.getName(), null);
            item.setId(menu.getId());
            item.setPid(menu.getPid());
            item.setMenuType(menu);
            item.setUrl(StringUtils.trimToEmpty(menu.getUrl()));
            item.setOrderNum(menu.getOrderNum());
            if(item.isRootMenu()) {
                root.put(item.getId(), item);
            }
        }
        for (Menu menu : menus) {
            MenuItem item = new MenuItem(menu.getName(), null);
            item.setId(menu.getId());
            item.setPid(menu.getPid());
            item.setMenuType(menu);
            item.setUrl(StringUtils.trimToEmpty(menu.getUrl()));
            item.setOrderNum(menu.getOrderNum());
            if(!item.isRootMenu() && !item.isButton()) {
                MenuItem parentItem = root.get(item.getPid());
                if(parentItem != null) {
                    parentItem.addClild(item);
                } else {
                    logger.warn("菜单项{}({})没有对应的父级菜单", item.getName(), item.getId());
                }
            }
        }
        return root.values();
    }
}